package com.string.actortv.activity.jxtcd;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.string.actortv.R;
import com.string.actortv.activity.AliPlayerActivity;
import com.string.actortv.dto.MovieInfo;
import com.string.actortv.dto.MovieList;
import com.string.actortv.enums.PlayerType;
import com.string.actortv.util.JxtcdUtil;
import com.string.actortv.util.SQLiteHelper;
import com.string.actortv.util.UIHelper;

import java.util.ArrayList;
import java.util.HashMap;


public class JxtcdSeasonActivity extends Activity {

    private Context mContext;
    private SimpleAdapter gridAdapter;
    private GridView gridView;
    private View selectedView;
    private ArrayList<HashMap<String, Object>> items;
    private SQLiteHelper sqLiteHelper;

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                default:
                    if (gridAdapter != null) {
                        gridAdapter.notifyDataSetChanged();
                    }
            }
            return true;
        }
    });

    // Activity OnCreate
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_season_list);
        mContext = this;
        sqLiteHelper = new SQLiteHelper(mContext);

        this.newInit(getIntent());
    }

    private void loadSeasonList(Intent intent) {
        MovieList nowMovie = JSONObject.parseObject(intent.getDataString(), MovieList.class);
        UIHelper.showDialogForLoading(mContext, "正在加载...");
        JxtcdUtil.getMovieInfoAsync(nowMovie.getHref(), nowMovie.getName(), movieInfo -> {
            if (movieInfo == null) {
                Log.d("list-retry", "重新尝试连接");
                loadSeasonList(intent);
                return;
            }
            for (MovieInfo.SeasonList seasonList : movieInfo.getSeasonList()) {
                HashMap<String, Object> item = new HashMap<>();
                item.put("title", movieInfo.getName() + "[" + seasonList.getName() + "]");
                item.put("icon", nowMovie.getImgUrl());
                item.put("url", seasonList.getUrl());

                items.add(item);
            }

            handler.sendMessage(new Message());
            UIHelper.dismiss();
        });
    }

    // initiate new UI content
    private void newInit(Intent intent) {
        items = new ArrayList<>();
        this.gridView = this.findViewById(R.id.item_grid);
        if (gridView == null) {
            throw new IllegalArgumentException("the gridView is null");
        }

        //异步加载数据
        loadSeasonList(intent);
        this.gridAdapter = new SimpleAdapter(this, items,
                R.layout.function_block, new String[]{"title", "icon"},
                new int[]{R.id.Item_text, R.id.Item_bt});
        gridAdapter.setViewBinder((view, data, textRepresentation) -> {
            //判断是否为我们要处理的对象
            if (view instanceof ImageView && data instanceof String) {
                ImageView iv = (ImageView) view;
                Glide.with(this).load(data.toString()).error(R.drawable.no_pic).into(iv);
                return true;
            } else {
                return false;
            }
        });
        this.gridView.setAdapter(gridAdapter);
        this.gridAdapter.notifyDataSetChanged();

        this.gridView.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                if (selectedView != null) {
                    selectedView.setBackgroundColor(Color.WHITE);
                }
                View first = gridView.getChildAt(0);
                if (first != null) {
                    first.setBackgroundColor(Color.GRAY);
                    selectedView = first;
                }
            } else {
                if (selectedView != null) {
                    selectedView.setBackgroundColor(Color.WHITE);
                    selectedView = null;
                }
            }
        });

        this.gridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (selectedView != null) {
                    selectedView.setBackgroundColor(Color.WHITE);
                }
                if (view != null) {
                    view.setBackgroundColor(Color.GRAY);
                    selectedView = view;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                if (selectedView != null) {
                    selectedView.setBackgroundColor(Color.WHITE);
                    selectedView = null;
                }
            }

        });

        this.gridView.setOnItemClickListener((gridView, view, position, id) -> {
            UIHelper.showDialogForLoading(mContext, "正在加载...");
            Intent intent1 = new Intent(JxtcdSeasonActivity.this,
                    AliPlayerActivity.class);
            //重新记录历史记录
            JxtcdUtil.getMovieUrlAsync(items.get(position).get("url").toString(), (playUrl) -> {
                String title = items.get(position).get("title").toString() + "-0%";
                //查找是否存在历史记录
                Cursor cursor = sqLiteHelper.queryHistoryByUrl(items.get(position).get("url").toString());
                if (cursor.getCount() > 0) {
                    cursor.moveToPosition(0);
                    intent1.putExtra("hisTimes", cursor.getLong(5));
                    sqLiteHelper.deleteHistoryByUrl(items.get(position).get("url").toString());
                    title = cursor.getString(1);
                }
                sqLiteHelper.insertHistory(title, items.get(position).get("icon").toString(),
                        items.get(position).get("url").toString(), playUrl, 0L, PlayerType.JXTCD.getCode());
                intent1.putExtra("url", items.get(position).get("url").toString());
                intent1.putExtra("playUrl", playUrl);
                UIHelper.dismiss();
                startActivity(intent1);
            });
        });
    }

}
